package com.tbq.game.service.http

import com.yanzhenjie.kalle.*
import com.yanzhenjie.kalle.simple.Callback
import com.yanzhenjie.kalle.simple.SimpleResponse
import java.io.File
import java.lang.Exception

object BaseHttp {
    inline fun <reified T> request(
        url: String,
        requestMethod: RequestMethod,
        headerMap: Map<String, String>?,
        paramMap: Map<String, Any>?,
        lintener: OnHttpListener<T>
    ) {
        val headers = Headers()
        headerMap?.forEach { headers.add(it.key, it.value) } //处理Header
        val params = Params.newBuilder()
        paramMap?.forEach {
            when (it.value.javaClass) {
                String::class.java->params.add(it.key, it.value.toString())
                Int::class.java->params.add(it.key, it.value.toString().toInt())
                Long::class.java->params.add(it.key, it.value.toString().toLong())
                Boolean::class.java->params.add(it.key, it.value.toString().toBoolean())
                Double::class.java->params.add(it.key, it.value.toString().toDouble())
                Float::class.java->params.add(it.key, it.value.toString().toFloat())
                Short::class.java->params.add(it.key, it.value.toString().toShort())
                File::class.java->params.file(it.key,it.value as File)
                Binary::class.java->params.binary(it.key,it.value as Binary)
            }
        }//处理Header
        val callback = object : Callback<T, String>() {
            override fun onResponse(response: SimpleResponse<T, String>?) {
                lintener.onSaveLog(response, response?.succeed())
                lintener.onSuccess(response, response?.succeed())

            }

            override fun onCancel() {
                lintener.onCancel()
            }

            override fun onException(e: Exception?) {
                lintener.onFailed(e)
            }

            override fun onEnd() {
                lintener.onFinish()
            }

            override fun onStart() {
                lintener.onStart()
            }
        }
        when (requestMethod) {
            RequestMethod.POST -> Kalle.post(url).setHeaders(headers).setParams(params.build()).perform(callback)
            RequestMethod.PUT -> Kalle.post(url).setHeaders(headers).setParams(params.build()).perform(callback)
            RequestMethod.DELETE -> Kalle.post(url).setHeaders(headers).setParams(params.build()).perform(callback)
            else -> Kalle.get(url).setHeaders(headers).setParams(params.build()).perform(callback)
        }
    }
}